from serial import Serial
from time import sleep
#import threading
from PyQt4.QtCore import QObject, SIGNAL, QThread
import common

SerialSettings = {  'port'      : 'com1',
                    'baund'     : 115200,
                    'bytesize'  : 8,
                    'stopbits'  : 1,
                    'parity'    : 'N',
                    'timeout'   : 300
            }

class DriverSerial(QThread):    
    def __init__(self, parent = None):
        super(DriverSerial, self).__init__(parent)
        self.recvThreadRun = False
        self.qObj = QObject()

    def open(self):
        common.debug(__name__, 'open')       
        try:
            self.serial = Serial(SerialSettings['port'], SerialSettings['baund'], SerialSettings['bytesize'],\
                    SerialSettings['parity'], SerialSettings['stopbits'], SerialSettings['timeout'])
            self.serial.flushInput()
            self.serial.flushOutput()
            self.start()
        except Exception, msg:
            return False, msg.message.decode('gbk')
        return True, 'success'
 
    def close(self):
        common.debug(__name__, 'close')        
        if self.recvThreadRun:
            self.recvThreadRun = False
            self.serial.close()

    def send(self, data):
        common.debug(__name__, data)
        self.serial.write(data)

    def recv(self):
        data = None
        while self.recvThreadRun:
            data = self.serial.read(1)
            if not data:
                continue
            else:
                n = self.serial.inWaiting()
                if n > 0:
                    data = '%s%s' % (data, self.serial.read(n))
                    sleep(0.01)  
                return data
        return False
  
    def run(self):
        self.recvThreadRun = True
        while self.recvThreadRun:
            data = self.recv()
            if data:
                self.qObj.emit(SIGNAL('SerialRecvData'), data)
                
if __name__ == '__main__':
    ds = DriverSerial()
    if ds.open():
        ds.recv()
        ds.close()
    else:
        ds.close()  
